package swordoffer.offer41;

import java.util.ArrayList;
import java.util.PriorityQueue;

public class HeapSolution {
    class MedianFinder {

        private PriorityQueue<Integer> minHeap;
        private PriorityQueue<Integer> maxHeap;

        /**
         * initialize your data structure here.
         */
        public MedianFinder() {
            this.minHeap = new PriorityQueue<>((a, b) -> (a - b));
            this.maxHeap = new PriorityQueue<>((a, b) -> (b - a));
        }

        public void addNum(int num) {
            // 如果两个堆的大小相等，将元素添加到小根堆中，再将小根堆的堆顶元素加入到大根堆，这样可以保证大根堆中的元素小于等于小根堆中的元素
            if (minHeap.size() == maxHeap.size()) {
                minHeap.offer(num);
                maxHeap.offer(minHeap.poll());
            } else {
                maxHeap.offer(num);
                minHeap.offer(maxHeap.poll());
            }
        }

        public double findMedian() {
            if (maxHeap.size() == minHeap.size()) {
                return (maxHeap.peek() + minHeap.peek()) / 2.0;
            }
            // 由于两个堆大小相等时，将元素添加到最大堆中，所以最大堆的堆顶即为中位数
            return (double) maxHeap.peek();
        }
    }
}
